package com.tuo51.childcare.service.impl;


import com.tuo51.childcare.domain.photoalbum.PhotoAlbum;
import com.tuo51.childcare.domain.photoalbum.PhotoAlbumTemplate;
import com.tuo51.childcare.domain.photoalbum.PhotoAlbumTemplatePage;
import com.tuo51.childcare.repository.photoAlbum.PhotoAlbumRepository;
import com.tuo51.childcare.repository.photoAlbum.PhotoAlbumTemplatePageRepository;
import com.tuo51.childcare.repository.photoAlbum.PhotoAlbumTemplateRepository;
import com.tuo51.childcare.service.PhotoAlbumService;
import com.tuo51.evaluate.domain.childrens.Children;
import com.tuo51.evaluate.repositories.children.ChildrenRepository;
import com.tuo51.evaluate.service.UploadService;
import com.tuo51.foudation.constant.LiveRecordConstant;
import com.tuo51.foudation.exception.BusinessException;
import com.tuo51.foudation.model.ErrorCode;
import com.tuo51.foudation.query.base.PagerQuery;
import com.tuo51.foudation.utils.CopyUtils;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.io.*;
import java.util.List;
import java.util.Map;

import static com.tuo51.foudation.model.ErrorCode.JSON_STR_ERROR;


@Service
public class PhotoAlbumServiceImpl implements PhotoAlbumService {

    @Autowired
    PhotoAlbumRepository albumRepository;

    @Autowired
    PhotoAlbumTemplatePageRepository pageRepository;

    @Autowired
    PhotoAlbumTemplateRepository templateRepository;

    @Autowired
    ChildrenRepository childrenRepository;

//    @Autowired
//    LiveRecordRepository liveRecordRepository;
//
//    @Autowired
//    ObservationNewRepository observationRepository;

    @Autowired
    UploadService uploadService;

    @Value("${album.photo.templateName}")
    String templateFileName;

    @Override
    public Page<PhotoAlbum> childrenAlbumPage(String childrenId, PagerQuery pagerQuery) {
        PageRequest pr = PageRequest.of(pagerQuery.getPageNum(), pagerQuery.getPageSize());
        return albumRepository.findByChildrenIdOrderByCreatedDesc(childrenId, pr );
    }

    @Override
    public PhotoAlbum photoAlbumById(String albumId) {
        return albumRepository.getOne(albumId);
    }

    @Override
    public PhotoAlbum createPhotoAlbum(String childrenId, String areaId, String areaName, String json) {
        Children c = childrenRepository.getOne(childrenId);
        if(null == c){
            throw new BusinessException(ErrorCode.CHILDREN_NOT_EXIST, "宝宝不存在");
        }

        PhotoAlbum pa = PhotoAlbum.of(c.getName(), c.getId(), c.getNickName(), c.getGender(), json, 0, false);
//        pa.setAreaName(areaName);
        albumRepository.save(pa);

        //TODO 静态化
        try {
            pa.setStaticURL(staticfyPhotoAlbum(CopyUtils.transBean2Map(pa)));
            albumRepository.save(pa);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ErrorCode.ERROR, "静态化文件时出错");
        }

        return pa;
    }

    @Override
    public Page<String> getAllValidPhotoURL(String childrenId, String areaId, PagerQuery pagerQuery) {

        PageRequest pr = PageRequest.of(pagerQuery.getPageNum(), pagerQuery.getPageSize());

        int mediaType = LiveRecordConstant.MediaType.IMG.codeOf();

        //TODO: 查找家长观测点发送的内容
        int beginRow = pagerQuery.getPageNum() * pagerQuery.getPageSize();
        int size = pagerQuery.getPageSize();
//        List<LiveRecord> records = liveRecordRepository.findAllValidPhotos(areaId, childrenId, beginRow, size );
//        int count = liveRecordRepository.countValidPhotos(areaId, childrenId);
//
//        List<String> images = records.stream().map(k ->{
//            return k.getResourceUrl();
//        }).collect(Collectors.toList());
        List<String> images = null;
        int count = 0;
        Page<String> result = new PageImpl<String>(images, pr, count);

        return result;
    }

    public List<PhotoAlbumTemplate> getAllTemplates(String areaId){
        return templateRepository.findAllByAreaId(areaId);
    }

    public List<PhotoAlbumTemplatePage> getAllTemplatePages(String templateId){
        return pageRepository.findAllByTemplateIdOrderByCapacityDesc(templateId);
    }



    ///// for static res

    //配置信息
    private static Configuration configuration = null;

    //这里注意的是利用WordUtils的类加载器动态获得模板文件的位置
//    private static String templateFolder ;

    //临时文件写出路径
    private static final String tempPath =  "/tmp/photo_album";
            //PhotoAlbumTemplate.class.getClassLoader().getResource(".").getPath() + "temp";

    public String staticfyPhotoAlbum(Map<String, Object> map)  {

        Writer out = null;

        String url = tempPath + "/" + map.get("id")+".html";

        //创建文件夹
        File tf = new File(tempPath);
        if(!tf.exists()){
            Boolean success = tf.mkdirs();
            if(success){
                System.out.println("create file success::" + tempPath);
            }
        }

        try {
            Template temple = configuration.getTemplate(templateFileName);//获取模板

            out = new OutputStreamWriter(new FileOutputStream(url));//生成最终页面并写到文件

            temple.process(map, out);//处理

            String uploadedResult = uploadService.uploadStaticPhotoAlbum(url);

            return uploadedResult;
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                out.close();
            } catch (IOException e) {

            }

            File file = new File(url);
            if(file.exists()) {
                file.delete();
            }
        }

        throw new BusinessException(JSON_STR_ERROR, "生成相册出错");
    }
}
